package Controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import Model.Contact;
import Model.Group;
import View.FormView;

/**
 * implements the action for the form view
 * 
 * @author Vincent Francolin
 * @version 1.0 : creation
 */
public class FormActionListener implements ActionListener {
	FormView obj;
	ContactController ctrl;
	Contact prev;

	/**
	 * default constructor
	 * 
	 * @param obj
	 *            the form view object
	 * @param ctrl
	 *            the main controller of the application
	 * @param prev
	 *            the previous contact in case of modification null otherwise
	 */
	public FormActionListener(FormView obj, ContactController ctrl, Contact prev) {
		super();
		this.obj = obj;
		this.ctrl = ctrl;
		this.prev = prev;
	}

	/**
	 * method called when a button is clicked
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		JButton src = (JButton) e.getSource();

		if (src.getText().equals("Save")) {
			Contact cnt = obj.getContactFromEntries();
			Group grp = obj.getGroupFromEntries();
			if (prev != null){
				prev = cnt;
				ctrl.getContactRecord(ctrl.getCurrentSelected()).setGroup(grp);
			}
			else if (cnt != null)
				ctrl.addContact(cnt, grp);
			else
				JOptionPane.showMessageDialog(null,
						"Some field are empty, please fill al field!");
		} else if (src.getText().equals("Change picture")) {
			JFileChooser winFile = new JFileChooser();
	        FileNameExtensionFilter filter = new FileNameExtensionFilter(
	                "Picture (*.png,*.jpg,*.bmp)", "png","jpg","jpeg","bmp");
	        winFile.setFileFilter(filter);
	        int returnVal = winFile.showOpenDialog(null);
	        if (returnVal == JFileChooser.APPROVE_OPTION) {
	            File file = winFile.getSelectedFile();
	            String filename = file.getName();
	            System.out.println(filename+" "+file.getAbsolutePath());
	            try {
	            	if(!Files.exists(Paths.get("images/")))
	            		Files.createDirectory(Paths.get("images/"));
	            	Path origin = Paths.get(file.getAbsolutePath());
	            	Path dest =  Paths.get("images/"+filename);
	            	if(origin==null) System.out.println("Error on origin");
	            	if(dest==null) System.out.println("Error on dest");
					Files.copy(origin,dest);
					obj.setPicPath(filename);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	        }
		}
	}

}
